package com.example.grpc;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

/**
 * 管理{@code Greeter}服务器启动/关闭的服务器。
 */
public class GreeterServer {
  private static final Logger logger = Logger.getLogger(GreeterServer.class.getName());

  private Server server;

  private void start() throws IOException {
    /* 服务器应该运行的端口 */
    int port = 50051;
    server = ServerBuilder.forPort(port)
        .addService(new GreeterImpl())
        .build()
        .start();
    logger.info("Server started, listening on " + port);
    Runtime.getRuntime().addShutdownHook(new Thread() {
      @Override
      public void run() {
        // 在这里使用stderr，因为日志记录器可能已被其JVM关闭钩子重置。
        System.err.println("*** 由于JVM正在关闭，正在关闭gRPC服务器");
        try {
          GreeterServer.this.stop();
        } catch (InterruptedException e) {
          e.printStackTrace(System.err);
        }
        System.err.println("*** 服务器已关闭");
      }
    });
  }

  private void stop() throws InterruptedException {
    if (server != null) {
      try {
        server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
      } catch (NoClassDefFoundError e) {
        // 忽略JVM关闭时的类加载问题
        System.err.println("Ignoring NoClassDefFoundError during shutdown: " + e.getMessage());
      } catch (Exception e) {
        System.err.println("Error during server shutdown: " + e.getMessage());
      }
    }
  }

  /**
   * 在主线程上等待终止，因为grpc库使用守护线程。
   */
  private void blockUntilShutdown() throws InterruptedException {
    if (server != null) {
      server.awaitTermination();
    }
  }

  /**
   * Main方法从命令行启动服务器。
   */
  public static void main(String[] args) throws IOException, InterruptedException {
    final GreeterServer server = new GreeterServer();
    server.start();
    server.blockUntilShutdown();
  }

  static class GreeterImpl extends GreeterGrpc.GreeterImplBase {

    @Override
    public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
      HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();
      responseObserver.onNext(reply);
      responseObserver.onCompleted();
    }

    @Override
    public void sayHelloAgain(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
      HelloReply reply = HelloReply.newBuilder().setMessage("Hello again " + req.getName()).build();
      responseObserver.onNext(reply);
      responseObserver.onCompleted();
    }
  }
}